package com.xoa.service.inv;

import com.xoa.dao.crm.SupplierMapper;
import com.xoa.dao.inv.InvWarehouseMapper;
import com.xoa.dao.inv.PoCommodityOutMapper;
import com.xoa.dao.inv.ProductTypeMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.crm.Supplier;
import com.xoa.model.inv.InvWarehouse;
import com.xoa.model.inv.PoCommodityOut;
import com.xoa.model.inv.ProductType;
import com.xoa.model.users.Users;
import com.xoa.util.CookiesUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.page.PageParams;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class PoCommodityOutService {
    @Resource
    private PoCommodityOutMapper poCommodityOutMapper;
    @Resource
    private ProductTypeMapper productTypeMapper;
    @Resource
    private SupplierMapper supplierMapper;
    @Resource
    private UsersMapper usersMapper;
    @Resource
    private InvWarehouseMapper invWarehouseMapper;

    public ToJson<PoCommodityOut> insertProductOut(HttpServletRequest request, PoCommodityOut poCommodityOut) {
        ToJson<PoCommodityOut> toJson =new ToJson<PoCommodityOut>(1,"err");
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionCookie);
        try {
            //生成单据号
            Date date = new Date();//当前日期---生成单据号的主要因素
            DateFormat format=new SimpleDateFormat("yyyyMMdd");
            String timeStr=format.format(date);
            String stt = "NO";//固定前缀
            int newNumber = 00001;//自增编号
            String documentNo = "";
            if(poCommodityOut!=null){
                List<PoCommodityOut> list = poCommodityOutMapper.selectProductInfoAll();
                if(list.size()>0&&list!=null){
                    if(list.get(0).getDocumentNo()!=null&& !list.get(0).getDocumentNo().isEmpty()){
                        String str = list.get(0).getDocumentNo();
                        String s=str.substring(str.length()-5);
                        int newNo = Integer.parseInt(s);
                        newNo++;

                        String str1=Integer.toString(newNo);
                        while(str1.length()<5)
                        {
                            str1="0"+str1;
                        }
                        documentNo = stt + timeStr + str1;
                    }
                    poCommodityOut.setDocumentNo(documentNo);
                }else {
                    String dtr = String.format("%05d", newNumber);
                    documentNo =stt + timeStr + dtr;
                    poCommodityOut.setDocumentNo(documentNo);
                }

            }
            //入库人
            if(poCommodityOut.getUserId()!=null){
                poCommodityOut.setUserId(poCommodityOut.getUserId());
            }else {
                poCommodityOut.setUserId(users.getUserId());
            }
            int count=poCommodityOutMapper.insertSelective(poCommodityOut);
            if(count>0){
                toJson.setObject(poCommodityOut);
                toJson.setMsg("ok");
                toJson.setFlag(0);
            }

        } catch (Exception e) {
            e.printStackTrace();
            toJson.setFlag(1);
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }

    public ToJson<PoCommodityOut> updateProduct(HttpServletRequest request, PoCommodityOut poCommodityOut) {
        ToJson<PoCommodityOut> toJson =new ToJson<PoCommodityOut>(1,"err");
        try {
            int count=poCommodityOutMapper.updateByPrimaryKeySelective(poCommodityOut);
            if(count>0){
                toJson.setObject(poCommodityOut);
                toJson.setMsg("ok");
                toJson.setFlag(0);
            }

        } catch (Exception e) {
            e.printStackTrace();
            toJson.setFlag(1);
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }

    public ToJson<PoCommodityOut> selectProductById(HttpServletRequest request, Integer retreatId) {
        ToJson<PoCommodityOut> toJson =new ToJson<PoCommodityOut>(1,"err");
        try {
            PoCommodityOut poCommodityOut=poCommodityOutMapper.selectByPrimaryKey(retreatId);
            if(poCommodityOut!=null){
                //商品大类名称
                if(!StringUtils.checkNull(poCommodityOut.getProductType())&&poCommodityOut.getProductType()!=""){
                    ProductType productType = productTypeMapper.selectByPrimaryKey(Integer.valueOf(poCommodityOut.getProductType()));
                    if(productType!=null){
                        poCommodityOut.setProductName(productType.getProductTypeName());
                    }
                }
                //供应商名称
                if(poCommodityOut.getSupplierId()!=0&&poCommodityOut.getSupplierId()!=null){
                    Supplier supplier = supplierMapper.selectByPrimaryKey(poCommodityOut.getSupplierId());
                    if(supplier!=null){
                        poCommodityOut.setSupplierName(supplier.getSupplierName());
                    }
                }
                //入库人名称
                if(poCommodityOut.getUserId()!=""&&poCommodityOut.getUserId()!=null){
                    Users users = usersMapper.getUserId(poCommodityOut.getUserId());
                    if(users!=null){
                        poCommodityOut.setUserName(users.getUserName());
                    }
                }
                //仓库名称
                if(poCommodityOut.getWarehouseId()!=0&&poCommodityOut.getWarehouseId()!=null){
                    InvWarehouse invWarehouse = invWarehouseMapper.selectByPrimaryKey(poCommodityOut.getWarehouseId());
                    if(invWarehouse!=null){
                        poCommodityOut.setWarehouseName(invWarehouse.getWarehouseName());
                    }
                }
            }
            if(poCommodityOut!=null){
                toJson.setObject(poCommodityOut);
                toJson.setMsg("ok");
                toJson.setFlag(0);
            }

        } catch (Exception e) {
            e.printStackTrace();
            toJson.setFlag(1);
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }

    public ToJson<PoCommodityOut> deleteProductById(HttpServletRequest request, Integer retreatId) {
        ToJson<PoCommodityOut> toJson =new ToJson<PoCommodityOut>(1,"err");
        try {
            poCommodityOutMapper.deleteByPrimaryKey(retreatId);
            toJson.setMsg("ok");
            toJson.setFlag(0);
        } catch (Exception e) {
            e.printStackTrace();
            toJson.setFlag(1);
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }

    public ToJson<PoCommodityOut> selectProductInfo(HttpServletRequest request, PoCommodityOut poCommodityOut,Integer page, Integer pageSize) {
        ToJson<PoCommodityOut> toJson =new ToJson<PoCommodityOut>(1,"err");
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            PageParams pageParams = new PageParams();
            pageParams.setUseFlag(true);
            pageParams.setPage(page);
            pageParams.setPageSize(pageSize);
            map.put("obj", poCommodityOut);
            map.put("page", pageParams);
            Map<String, Object> map2 = new HashMap<String, Object>();
            map2.put("obj", poCommodityOut);
            List<PoCommodityOut> list=poCommodityOutMapper.selectProductInfo(map);
            if(list!=null&&list.size()>0){
                for(int i=0;i<list.size();i++){
                    //商品大类名称
                    if(!StringUtils.checkNull(list.get(i).getProductType())&&list.get(i).getProductType()!=""){
                        ProductType productType = productTypeMapper.selectByPrimaryKey(Integer.valueOf(list.get(i).getProductType()));
                        if(productType!=null){
                            list.get(i).setProductName(productType.getProductTypeName());
                        }
                    }
                    //供应商名称
                    if(!StringUtils.checkNull(list.get(i).getSupplierId()+"")&&!"0".equals(list.get(i).getSupplierId()+"")){
                        Supplier supplier = supplierMapper.selectByPrimaryKey(list.get(i).getSupplierId());
                        if(supplier!=null){
                            list.get(i).setSupplierName(supplier.getSupplierName());
                        }
                    }
                    //入库人名称
                    if(list.get(i).getUserId()!=""&&list.get(i).getUserId()!=null){
                        Users users = usersMapper.getUserId(list.get(i).getUserId());
                        if(users!=null){
                            list.get(i).setUserName(users.getUserName());
                        }
                    }
                    //仓库名称
                    if(!StringUtils.checkNull( list.get(i).getWarehouseId()+"")&&!"0".equals( list.get(i).getWarehouseId()+"")      ){
                        InvWarehouse invWarehouse = invWarehouseMapper.selectByPrimaryKey(list.get(i).getWarehouseId());
                        if(invWarehouse!=null){
                            list.get(i).setWarehouseName(invWarehouse.getWarehouseName());
                        }
                    }
                    //退货人
                    if(list.get(i).getUserId()!=null&&list.get(i).getUserId()!=""){
                        /*String substring = list.get(i).getUserId().substring(0,list.get(i).getUserId().indexOf(","));
                        list.get(i).setUserName(usersMapper.findUsersByuserId(substring).getUserName());*/

                        String[] split = list.get(i).getUserId().split(",");
                        List<Users> usersByUids = usersMapper.getUsersByUserIds(split);
                        StringBuffer sb = new StringBuffer();
                        for (Users u : usersByUids) {
                            sb.append(u.getUserName() + ",");
                        }
                        list.get(i).setUserName(sb.toString());
                    }

                    //合计 =单价*数量
                    if(list.get(i).getRetreatOutprice()!=null && list.get(i).getRetreatNum()!=null){
                        double d=list.get(i).getRetreatOutprice()*list.get(i).getRetreatNum();
                        //String format = String.format("%.1f", d);
                        list.get(i).setRetreatTotal(d);
                    }
                }
                toJson.setObj(list);
                toJson.setTotleNum(poCommodityOutMapper.selectProductInfo2(map2));
                toJson.setMsg("ok");
                toJson.setFlag(0);
            }

        } catch (Exception e) {
            e.printStackTrace();
            toJson.setFlag(1);
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }


//多条件查询
    public ToJson<PoCommodityOut> selectAll(Map<String, Object> map) {
        //SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        ToJson<PoCommodityOut> toJson =new ToJson<PoCommodityOut>(1,"err");
        try {
            List<PoCommodityOut> list=poCommodityOutMapper.selectAll(map);
            if(list!=null&&list.size()>0){
                for(PoCommodityOut poCommodityOut1:list){
                    //商品大类名称
                    if(!StringUtils.checkNull(poCommodityOut1.getProductType())&&poCommodityOut1.getProductType()!=""){
                        ProductType productType = productTypeMapper.selectByPrimaryKey(Integer.valueOf(poCommodityOut1.getProductType()));
                        if(productType!=null){
                            poCommodityOut1.setProductName(productType.getProductTypeName());
                        }
                    }
                    //供应商名称
                    if(!StringUtils.checkNull(String.valueOf(poCommodityOut1.getSupplierId()))){
                        Supplier supplier = supplierMapper.selectByPrimaryKey(poCommodityOut1.getSupplierId());
                        if(supplier!=null){
                            poCommodityOut1.setSupplierName(supplier.getSupplierName());
                        }
                    }
                    //入库人名称
                    if(!StringUtils.checkNull(poCommodityOut1.getUserId())){
                        Users users = usersMapper.getUserId(poCommodityOut1.getUserId());
                        if(users!=null){
                            poCommodityOut1.setUserName(users.getUserName());
                        }
                    }
                    //仓库名称
                    if(!StringUtils.checkNull(String.valueOf(poCommodityOut1.getWarehouseId()))){
                        InvWarehouse invWarehouse = invWarehouseMapper.selectByPrimaryKey(poCommodityOut1.getWarehouseId());
                        if(invWarehouse!=null){
                            poCommodityOut1.setWarehouseName(invWarehouse.getWarehouseName());
                        }
                    }
                    //退货人
                    if(!StringUtils.checkNull(poCommodityOut1.getUserId())){
                        /*String substring = list.get(i).getUserId().substring(0,list.get(i).getUserId().indexOf(","));
                        list.get(i).setUserName(usersMapper.findUsersByuserId(substring).getUserName());*/

                        String[] split = poCommodityOut1.getUserId().split(",");
                        List<Users> usersByUids = usersMapper.getUsersByUserIds(split);
                        StringBuffer sb = new StringBuffer();
                        for (Users u : usersByUids) {
                            sb.append(u.getUserName() + ",");
                        }
                        poCommodityOut1.setUserName(sb.toString());
                    }

                    //合计 =单价*数量
                    if(StringUtils.checkNull(String.valueOf(poCommodityOut1.getRetreatOutprice()))){
                        double d=poCommodityOut1.getRetreatOutprice()*poCommodityOut1.getRetreatNum();
                       // String format = String.format("%.1f", d);
                        poCommodityOut1.setRetreatTotal(d);
                    }
                }
                toJson.setObj(list);
                toJson.setMsg("ok");
                toJson.setFlag(0);
            }

        } catch (Exception e) {
            e.printStackTrace();
            toJson.setFlag(1);
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }


    public ToJson<PoCommodityOut> selectProductOutByTypeId(HttpServletRequest request, String typeId) {
        ToJson<PoCommodityOut> toJson =new ToJson<PoCommodityOut>(1,"err");
        try {
            PoCommodityOut poCommodityOut=poCommodityOutMapper.selectProductOutByTypeId(typeId);
            if(poCommodityOut!=null){
                //供应商名称
                if(poCommodityOut.getSupplierId()!=0&&poCommodityOut.getSupplierId()!=null){
                    Supplier supplier = supplierMapper.selectByPrimaryKey(poCommodityOut.getSupplierId());
                    if(supplier!=null){
                        poCommodityOut.setSupplierName(supplier.getSupplierName());
                    }
                }
                //入库人名称
                if(poCommodityOut.getUserId()!=""&&poCommodityOut.getUserId()!=null){
                    Users users = usersMapper.getUserId(poCommodityOut.getUserId());
                    if(users!=null){
                        poCommodityOut.setUserName(users.getUserName());
                    }
                }
                //仓库名称
                if(poCommodityOut.getWarehouseId()!=0&&poCommodityOut.getWarehouseId()!=null){
                    InvWarehouse invWarehouse = invWarehouseMapper.selectByPrimaryKey(poCommodityOut.getWarehouseId());
                    if(invWarehouse!=null){
                        poCommodityOut.setWarehouseName(invWarehouse.getWarehouseName());
                    }
                }
            }
            if(poCommodityOut!=null){
                toJson.setObject(poCommodityOut);
                toJson.setMsg("ok");
                toJson.setFlag(0);
            }

        } catch (Exception e) {
            e.printStackTrace();
            toJson.setFlag(1);
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }
}
